package com.printer.printerexample;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.VibrateUtils;
import com.google.zxing.BarcodeFormat;
import com.printer.printerexample.entry.InventoryDetail;
import com.rsk.printerlibrary.ESC;
import com.rsk.printerlibrary.PrinterManager;
import com.rsk.printerlibrary.PrinterPort;
import com.rsk.printerlibrary.common.Printer_Params;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
    private static final String TAG = "MainActivity";
    BroadcastReceiver resultReceiver = null;//接受扫描到的数据的广播
    String BROADCAST_ACTION_SCAN_RESULT = "com.scanner.result";
    Button template_print, image_Test, inputTextTest, inputTextQrcode,
            bar_Test, qr_Test, printerCheck_Test, next, printSamllLabel;//,  printerTagTest;//
    Switch aSwitch_enable;
    TextView versionInfo, status, appversion;

    boolean markFlag = true;
    boolean isopen = false;
    boolean printering = false;
    private Bitmap BlackWhiteBitmap;//打印所需bitmap
    EditText inputText;
    ImageView imageView;
    PrinterManager manager;
    SeekBar seekBar;
    TextView seekText;
    int CurrentConcentration;//当前浓度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        template_print = findViewById(R.id.template_print);
        inputTextTest = findViewById(R.id.inputTextTest);
        inputTextQrcode = findViewById(R.id.inputTextQrcode);
        image_Test = findViewById(R.id.image_Test);
        bar_Test = findViewById(R.id.bar_Test);
        qr_Test = findViewById(R.id.qr_Test);
        printerCheck_Test = findViewById(R.id.printerCheck_Test);
        printSamllLabel = findViewById(R.id.printSmallLabel);
        inputText = findViewById(R.id.inputText);
        appversion = findViewById(R.id.appVersion);
        versionInfo=findViewById(R.id.printerVersion);
        aSwitch_enable = findViewById(R.id.blankMark_enable);
        imageView = findViewById(R.id.titleBg);

        seekText = findViewById(R.id.seekText);
        seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(this);

        template_print.setOnClickListener(this);
        inputTextTest.setOnClickListener(this);
        inputTextQrcode.setOnClickListener(this);
        image_Test.setOnClickListener(this);
        bar_Test.setOnClickListener(this);
        qr_Test.setOnClickListener(this);
        printerCheck_Test.setOnClickListener(this);
        printSamllLabel.setOnClickListener(this);
        aSwitch_enable.setOnClickListener(this);

        new Thread(() -> {
            initP();
        }).start();
        initBroadcast();
        manager = PrinterUtils.getManager();
        manager.PrintInit();
        seekBar.setMax(39);
        seekBar.setProgress(Integer.parseInt(seekText.getText().toString()));
    }


    @Override
    public void onClick(View v) {
        if (!isopen) return;

        if (checkPaper()) {
            ToastUtils.showLong("打印机缺纸！请重新装纸！");
            return;
        }
        if (printering) {
            ToastUtils.showLong(getString(R.string.pleaseWaitUntilThePrintingIsComplete));
            return;
        }
        printering = true;


        switch (v.getId()) {
            //模板打印
            case R.id.template_print: {
                String st = inputText.getText().toString().trim();
                if (!TextUtils.isEmpty(st)) {
                    printTemplate(st);
                } else {
                    ToastUtils.showLong(getString(R.string.inputCustomText));
                }
                break;
            }
            //打印字符串
            case R.id.inputTextTest: {

                String t = inputText.getText().toString().trim();
                if (!TextUtils.isEmpty(t)) {
                    printerText(t);
                } else {
                    ToastUtils.showLong(getString(R.string.inputCustomText));
                }

                break;
            }
            //打印二维码
            case R.id.inputTextQrcode: {
                String t = inputText.getText().toString().trim();
                if (!TextUtils.isEmpty(t)) {
                    printerQr(t);
                } else {
                    ToastUtils.showLong(getString(R.string.inputCustomText));
                }
                break;
            }

            //打印图片
            case R.id.image_Test: {
                printerImage();
                break;
            }
            //打印条形码
            case R.id.bar_Test: {
                String str_bar = inputText.getText().toString().trim();
                if (!TextUtils.isEmpty(str_bar)) {
                    printerBar(str_bar);
                } else {
                    ToastUtils.showLong(getString(R.string.inputCustomText));
                }
                break;
            }
            //停车收费小票打印
            case R.id.qr_Test: {

                printParkingFeeTemplate();


                break;
            }
            //打印机自检
            case R.id.printerCheck_Test: {
                printPrinterInfo();
                break;
            }
            //打印小标签
            case R.id.printSmallLabel: {
                printSmallLabel();
                break;
            }
            //黑标开启关闭
            case R.id.blankMark_enable: {
                if (aSwitch_enable.isChecked()) {
                    aSwitch_enable.setText(getString(R.string.openMark));
                    markFlag = true;
                    imageView.setBackgroundColor(getResources().getColor(R.color.DoderBlue));
                } else {
                    aSwitch_enable.setText(getString(R.string.offMark));
                    markFlag = false;
                    imageView.setBackgroundColor(getResources().getColor(R.color.Lavender));
                }
                break;
            }
        }
        printering = false;

    }

    void initP() {
        PrinterUtils.getInstance().init();
        isopen = true;
        String version = PrinterUtils.getInstance().getVersion();
        runOnUiThread(() -> {
//            versionInfo.setText("Printer V：" + version);
            Log.d(TAG, "version:" + version);
        });
        byte[] bytes2 = new byte[50];
        int le = ESC.getInstance().getBlackStatus(bytes2);//查询打印机黑标配置状态
        String string = new String(bytes2, 0, le);

        Log.d(TAG, "Build.MODEL==" + Build.MODEL);

        Log.d(TAG, "initP2:" + string);
        Log.d(TAG, "initP: 缺纸状态：" + checkPaper());
        getStatus();
        if (checkPaper()) {
            ToastUtils.showLong("请安装打印纸!");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregister();
        PrinterUtils.getInstance().destroy();
    }

    //接收扫描的广播数据
    private void initBroadcast() {
        if (resultReceiver == null) {
            resultReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String result = intent.getStringExtra("data");
                    inputText.append(result);
                }
            };
            IntentFilter filter = new IntentFilter();
            filter.addAction(BROADCAST_ACTION_SCAN_RESULT);
            registerReceiver(resultReceiver, filter);
        }
    }

    private void printParkingFeeTemplate() {
        if (PrintStrUtils.isZh(MainActivity.this)) {
            PrinterUtils.printText("XXX市停车收费", 1, Printer_Params.TEXT_ENLARGE.HEIGHT_WIDTH_DOUBLE);
            PrinterUtils.printText(PrintStrUtils.ParkingFeeChinese(), 0, Printer_Params.TEXT_ENLARGE.NORMAL);
            Bitmap bitmap3 = BitmapUtils.encode2dAsBitmap("1234567890", BarcodeFormat.QR_CODE, 180, 180);
            PrinterUtils.printBitmap(bitmap3, 1, bitmap3.getWidth(), bitmap3.getHeight());
            manager.PrintChars("--------------------------");
            PrinterUtils.getInstance().printBarCode("0123456789");
            manager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
            manager.PrintChars("--------------------------");
            PrinterUtils.printText("收费金额：54元", 0, Printer_Params.TEXT_ENLARGE.HEIGHT_WIDTH_DOUBLE);
            PrinterUtils.printText(PrintStrUtils.ParkingFeeChinese1(), 0, Printer_Params.TEXT_ENLARGE.NORMAL);
            if (markFlag) {
                manager.PrintBlackSearch();
            } else {
                manager.PrintLines(4);
            }
        } else {
            PrinterUtils.printText("Parking fees in XXX", 1, Printer_Params.TEXT_ENLARGE.HEIGHT_WIDTH_DOUBLE);
            PrinterUtils.printText(PrintStrUtils.ParkingFeeEng(), 0, Printer_Params.TEXT_ENLARGE.NORMAL);
            Bitmap bitmap3 = BitmapUtils.encode2dAsBitmap("1234567890", BarcodeFormat.QR_CODE, 180, 180);
            PrinterUtils.printBitmap(bitmap3, 1, bitmap3.getWidth(), bitmap3.getHeight());
            manager.PrintChars("--------------------------");
            PrinterUtils.getInstance().printBarCode("0123456789");
            manager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
            manager.PrintChars("--------------------------");
            PrinterUtils.printText("Fee amount:54RMB", 0, Printer_Params.TEXT_ENLARGE.HEIGHT_WIDTH_DOUBLE);
            PrinterUtils.printText(PrintStrUtils.ParkingFeeEng1(), 0, Printer_Params.TEXT_ENLARGE.NORMAL);
            if (markFlag) {
                manager.PrintBlackSearch();
            } else {
                manager.PrintLines(4);
            }
        }
    }



    //打印机自检
    private void printPrinterInfo() {
        String printContent = "PrinterSelfCheck";

        if (markFlag) {

            PrinterManager mpManager = PrinterUtils.getManager();
            PrinterUtils.getManager().OpenBlackSearch();
            PrinterUtils.getInstance().printBlankLine(1);
            PrinterUtils.getInstance().printText("Printer Self Check\n\n", 1, Printer_Params.TEXT_ENLARGE.HEIGHT_DOUBLE);
            mpManager.PrintInit();
            PrinterUtils.getInstance().printText(getHandSetInfo(), 0);
            mpManager.PrintInit();
            PrinterUtils.getInstance().printBarCode("0123456789");
            mpManager.PrintQR(printContent);
            mpManager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
            PrinterUtils.getManager().PrintBlackSearch();
        } else {
            PrinterManager mpManagerR = PrinterUtils.getManager();

            PrinterUtils.getInstance().printText("Printer Self Check\n\n", 1, Printer_Params.TEXT_ENLARGE.HEIGHT_DOUBLE);
            mpManagerR.PrintInit();

//            PrinterUtils.getInstance().printText(getHandSetInfoR(), 0);
            mpManagerR.PrintChars(getHandSetInfoR());
            mpManagerR.PrintInit();
            PrinterUtils.getInstance().printBarCode("0123456789");
            mpManagerR.PrintQR(printContent);
            PrinterUtils.getInstance().printBlankLine(4);
            mpManagerR.PrintSetLayout(Printer_Params.ALIGN.CENTER);
        }

    }

    private String getHandSetInfo() {
        String handSetInfo = "Phone model:" + Build.MODEL + "\n"
                + "\nSystem Version:" + Build.VERSION.RELEASE + "\n"
                + "\nVersion Display:" + Build.DISPLAY + "\n"
                + "\nSDK Version:" + Build.VERSION.SDK_INT + "\n"
                + "\nROM Manufacture:" + Build.MANUFACTURER + "\n" // 这行返回的是rom定制商的名称
                + "\nPrint Bin Size：36.5*58mm\n"
                + "\nCamera：Front 8 million/rear 16 million pixels\n"
                + "\nDisplay screen: 5.5 inch, 720 * 1440 resolution\n"
                + "\nBattery:5V/3A, 3.8V/6300mAh";
        Log.e("tt", handSetInfo);
        return handSetInfo;
    }

    private String getHandSetInfoR() {
        String handSetInfo = "Phone model:" + Build.MODEL + "\n"
                + "\nSystem Version:" + Build.VERSION.RELEASE + "\n"
//                + "\nSerial Number:" + Build.getSerial()
                + "\nVersion Display:" + Build.DISPLAY + "\n"
//                + "\n系统定制商:" + Build.BRAND
//                + "\n设备参数:" + Build.DEVICE
//                + "\n开发代号:" + Build.VERSION.CODENAME
                + "\nSDK Version:" + Build.VERSION.SDK_INT + "\n"
//                + "\nCPU Type:" + Build.CPU_ABI+"\n"
//                + "\nHardware Type:" + Build.HARDWARE+"\n"
//                + "\n主机:" + Build.HOST
//                + "\n生产ID:" + Build.ID
                + "\nROM Manufacture:" + Build.MANUFACTURER + "\n" // 这行返回的是rom定制商的名称
                + "\nPrint Bin Size：36.5*58mm\n"
                + "\nCamera：Front 8 million/rear 16 million pixels, autofocus, and bright LED flash\n"
                + "\nDisplay screen: 5.5 inch, 720 * 1440 resolution,capacitance IPS high-definition screen, Multi-touch\n"
                + "\nBattery:5V/3A, 3.8V/6300mAh high-performance lithium polymer battery (detachable)";
        Log.e("tt", handSetInfo);
        return handSetInfo;
    }

    /**
     * 打印小标签
     */
    private void printSmallLabel() {
        Bitmap b1 = BitmapFactory.decodeResource(getResources(), R.drawable.picture3);
        int scay = b1.getWidth() / 300;
        Bitmap BlackWhiteBitmap = PrinterUtils.compressPic(b1, b1.getWidth() / scay, b1.getHeight() / scay);
        if (markFlag) {
            manager.OpenBlackSearch();
            manager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
            manager.PrintBitmap(BlackWhiteBitmap);
            manager.PrintBlackSearch();
        } else {
            manager.PrintInit();
            manager.PrintBitmap(BlackWhiteBitmap);
            manager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
            manager.PrintChars("\n\n\n\n\n");
        }
    }

    void unregister() {
        if (resultReceiver != null) {
            try {
                unregisterReceiver(resultReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    //检查是否缺纸状态   缺纸=true
    Boolean checkPaper() {
        byte[] bytes1 = new byte[50];
        int len = ESC.getInstance().getStatusInfo(bytes1, 50);//查询打印机状态
        return len == 1 && ((int) bytes1[0] & 0xFF) == 0x0C;
    }

    void getStatus() {
        byte[] bytes1 = new byte[50];
        PrinterPort.sendCtl(new byte[]{0x1d, 0x61, 0x00}, 3);
        int read = PrinterPort.read(bytes1, 50);
        int n = 0;
        while (read <= 0 && n++ < 8) {
            try {
                Thread.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            read = PrinterPort.read(bytes1, 50);
        }
        Log.d(TAG, "getStatus: 状态信息 " + ConvertUtils.bytes2HexString(bytes1));
    }


    //文本打印
    void printerText(String text) {
        Log.d("TAG", "printerText---markFlag:" + markFlag);
        if (markFlag) {
            PrinterUtils.getManager().OpenBlackSearch();
            PrinterUtils.getInstance().printBlankLine(1);
            PrinterUtils.getInstance().printText(text, 0);
            PrinterUtils.getManager().PrintBlackSearch();
        } else {
            PrinterUtils.getInstance().printText(text, 0);
            PrinterUtils.getInstance().printBlankLine(4);
        }
        PrinterManager mManager = PrinterUtils.getManager();
        mManager.PrintInit();
        mManager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
    }

    //打印二维码
    void printerQr(String text) {
        Bitmap bitmap3 = BitmapUtils.encode2dAsBitmap(text, BarcodeFormat.QR_CODE, 200, 200);
        if (markFlag) {
            PrinterUtils.getManager().OpenBlackSearch();
            PrinterUtils.printBitmap(bitmap3, 1, bitmap3.getWidth(), bitmap3.getHeight());
            PrinterUtils.getManager().PrintBlackSearch();
        } else {
            PrinterUtils.printBitmap(bitmap3, 1, bitmap3.getWidth(), bitmap3.getHeight());
//            manager.PrintChars("\n\n\n\n");
            PrinterManager mManager = PrinterUtils.getManager();
            mManager.PrintInit();
            mManager.PrintLines(4);
        }

    }

    //打印一维码
    void printerBar(String str_bar) {
        if (!isChinese(str_bar) && str_bar.length() <= 30) {
            Bitmap b1 = BitmapUtils.createBarcode(MainActivity.this, str_bar, 384, 90, true, 1);
            if (markFlag) {
                PrinterUtils.getManager().OpenBlackSearch();
                PrinterUtils.getInstance().printBlankLine(1);
                manager.PrintBitmap(b1);
                PrinterUtils.getManager().PrintBlackSearch();
            } else {
                manager.PrintBitmap(b1);
                manager.PrintChars("\n\n\n\n\n\n");
            }
        } else {
            Toast.makeText(MainActivity.this, getString(R.string.toast1), Toast.LENGTH_SHORT).show();
        }
    }

    // 判断一个字符串是否含有中文
    public boolean isChinese(String str) {
        if (str == null)
            return false;
        for (char c : str.toCharArray()) {
            if (isChineseC(c))
                return true;// 有一个中文字符就返回
        }
        return false;
    }

    // 判断一个字符是否是中文字符
    public boolean isChineseC(char c) {
        return c >= 0x4E00 && c <= 0x9FA5;// 根据字节码判断
    }


    //打印图片
    void printerImage() {

        Bitmap bitmap;//=stringtoBitmap(strImg);
        if (getResources().getConfiguration().locale.toString().contains("en")) {
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_1);
        } else {
            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bitmap);
        }
        BlackWhiteBitmap = PrinterUtils.convertToBlackWhite(bitmap);
        if (BlackWhiteBitmap != null) {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            int scay = width / 300;

            BlackWhiteBitmap = PrinterUtils.compressPic(BlackWhiteBitmap, 384, height / scay);
        }
        PrinterManager mManager = PrinterUtils.getManager();
        mManager.PrintInit();
        if (markFlag) {
            PrinterUtils.getManager().OpenBlackSearch();
            mManager.PrintBitmap(BlackWhiteBitmap);

            PrinterUtils.getManager().PrintBlackSearch();
        } else {
            mManager.PrintBitmap(BlackWhiteBitmap);
            mManager.PrintInit();
            PrinterUtils.getInstance().printBlankLine(4);
        }
    }

    //打印模板
    private void printTemplate(String str) {
        Bitmap bitmap = BitmapUtils.encode2dAsBitmap(str, BarcodeFormat.QR_CODE, 80, 80);
        InventoryDetail inventoryDetail = new InventoryDetail();
        inventoryDetail.setMaterialID("000001");
        inventoryDetail.setMaterialName("汽车方向盘");
        inventoryDetail.setModel("直径80");
        inventoryDetail.setEndAmount("432.00");
        inventoryDetail.setEndQuantity("12");
        inventoryDetail.setUnit("把");
        inventoryDetail.setUnitPrice("36.00");
        inventoryDetail.setHighestQuota("100");
        inventoryDetail.setLowestQuota("6");
        inventoryDetail.setWarehouseNumber("5");
        inventoryDetail.setId(1);
        PurchasePrint printView = new PurchasePrint(this);
        printView.setPrintText(this, inventoryDetail, bitmap);
        Bitmap printBitmap = BitmapUtils.loadBitmapFromView(printView);
        printBitmap = BitmapUtils.adjustPhotoRotation(printBitmap, 90);
        if (markFlag) {
            PrinterUtils.getManager().OpenBlackSearch();
            manager.PrintChars("\n");
            manager.PrintBitmap(printBitmap);
            PrinterUtils.getManager().PrintBlackSearch();
        } else {
            manager.PrintBitmap(printBitmap);
            manager.PrintInit();
            PrinterUtils.getInstance().printBlankLine(4);
        }
    }


    @Override
    protected void onRestart() {
        super.onRestart();
//        initP();
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                exitTime = System.currentTimeMillis();
                return true;
            }
        } else if (keyCode == 136) {
            if (event.getRepeatCount() == 0) {
                PrinterManager mManagers = PrinterUtils.getManager();
                mManagers.PrintInit();
                mManagers.PrintLines(1);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()) {
            finish();
        }
    }

    private void getSeekBarValue() {
        byte[] bs = new byte[50];
        int len = PrinterUtils.getManager().getprintConcentration(bs);
        Log.d("TAG", "showPrinterDeep: 浓度 ：" + new String(bs, 0, 10));
        String string = new String(bs, 0, CurrentConcentration);
        int l = 0;
        if (string.startsWith("level:")) {
            try {
                l = Integer.parseInt(string.replace("level:", "").trim());
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        seekBar.setProgress(CurrentConcentration);
        seekText.setText("" + CurrentConcentration);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        Log.d("TAG", "seekText.setText(\"\" + i); ：" + progress);
        switch (seekBar.getId()) {
            case R.id.seekBar:
                seekText.setText(String.valueOf(progress));
                Log.d("TAG", "seekText.setText(\"\" + i); ：" + progress);

                break;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        switch (seekBar.getId()) {
            case R.id.seekBar:
                Log.d("TAG", "onStartTrackingTouch() called with: seekBar = [" + seekBar + "]");
                break;
        }
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        switch (seekBar.getId()) {
            case R.id.seekBar:
                CurrentConcentration = seekBar.getProgress();
                PrinterUtils.getManager().printConcentration(seekBar.getProgress());
                break;
        }
    }
}